<template>
  <div class="app-container">
    <!--    <common-edit-dialog :visible="dialogShow"-->
    <!--                        :title="dialogTitle"-->
    <!--                        :button-loading="loading"-->
    <!--                        @cancel="close"-->
    <!--                        @submit="submit">-->
    <common-page title="设置密保问题">
      <el-button slot="header" @click="back">返 回</el-button>
      <div class="user-ques-edit-wrap" v-if="showQuesDialog" slot="content">
        <el-steps :active="active" finish-status="success" align-center>
          <el-step title="验证身份"></el-step>
          <el-step title="设置密保问题"></el-step>
          <el-step title="修改成功"></el-step>
        </el-steps>
        <div class="box" v-if="active === 0">
          <div class="mode-div">
            <div
              v-if="userForm.encodePhone"
              :class="activeTab === '1' ? 'active' : 'no-active'"
              @click="verifyChange('1')"
            >
              手机验证
            </div>
            <div
              v-if="userForm.encodeEmail"
              :class="activeTab === '2' ? 'active' : 'no-active'"
              @click="verifyChange('2')"
            >
              邮箱验证
            </div>
          </div>

          <div class="verify-list">
            <div class="verify-list-phone" v-if="activeTab === '1'">
              <div class="info">手机号{{ userForm.encodePhone }}</div>
              <div class="get-box">
                <div class="input-box">
                  <el-form ref="userForm" :model="userForm">
                    <el-form-item
                      prop="yzmPhone"
                      :rules="activeTab === '1' ? rules.yzmPhone : []"
                    >
                      <common-input
                        v-model="userForm.yzmPhone"
                        placeholder="请输入验证码"
                      ></common-input>
                      <div class="btn">
                        <div
                          class="item"
                          v-if="!phoneYzm"
                          :class="{ disabled: phoneYzm }"
                          @click="sendPhoneVerCodeForQueryPwdAnswer"
                        >
                          获取短信验证码
                        </div>
                        <div
                          class="item"
                          v-else
                          :class="{ disabled: phoneYzm }"
                        >
                          验证码已发送({{ phoneYzmTimes }}s)
                        </div>
                      </div>
                    </el-form-item>
                  </el-form>
                </div>
                <div class="notice">验证码{{ setValid }}分钟内有效！</div>
              </div>
            </div>

            <div class="verify-list-email" v-if="activeTab === '2'">
              <div class="info">邮箱{{ userForm.encodeEmail }}</div>
              <div class="get-box">
                <div class="input-box">
                  <el-form ref="userForm" :model="userForm">
                    <el-form-item
                      prop="yzmEmail"
                      :rules="activeTab === '2' ? rules.yzmEmail : []"
                    >
                      <common-input
                        v-model="userForm.yzmEmail"
                        placeholder="请输入验证码"
                      ></common-input>
                      <div class="btn">
                        <div
                          class="item"
                          v-if="!phoneYzm"
                          :class="{ disabled: phoneYzm }"
                          @click="sendEmailVerCodeForQueryPwdAnswer"
                        >
                          获取邮箱验证码
                        </div>
                        <div
                          class="item"
                          v-else
                          :class="{ disabled: phoneYzm }"
                        >
                          验证码已发送({{ phoneYzmTimes }}s)
                        </div>
                      </div>
                    </el-form-item>
                  </el-form>
                </div>
                <div class="notice">验证码{{ setValid }}分钟内有效！</div>
              </div>
            </div>
          </div>

          <el-button type="primary" @click="next('1')" :loading="nextLoading"
            >下一步</el-button
          >
        </div>
        <div class="question-list" v-if="active === 1">
          <el-form
            ref="form"
            :model="form"
            :rules="quesRules"
            label-width="120px"
          >
            <el-form-item label="密保问题一" prop="firstQuestionId">
              <el-select
                v-model="form.firstQuestionId"
                placeholder="请选择"
                style="width: 100%"
                @change="changeFun"
              >
                <el-option
                  v-for="item in questionList"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="密保问题一答案" prop="firstAnswer">
              <common-input v-model="form.firstAnswer"></common-input>
            </el-form-item>
            <el-form-item label="密保问题二" prop="secondQuestionId">
              <el-select
                v-model="form.secondQuestionId"
                placeholder="请选择"
                style="width: 100%"
                @change="changeFun"
              >
                <el-option
                  v-for="item in questionList"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="密保问题二答案" prop="secondAnswer">
              <common-input v-model="form.secondAnswer"></common-input>
            </el-form-item>
            <el-form-item label="密保问题三" prop="thirdQuestionId">
              <el-select
                v-model="form.thirdQuestionId"
                placeholder="请选择"
                style="width: 100%"
                @change="changeFun"
              >
                <el-option
                  v-for="item in questionList"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="密保问题三答案" prop="thirdAnswer">
              <common-input v-model="form.thirdAnswer"></common-input>
            </el-form-item>
          </el-form>
          <div class="submit-btn">
            <el-button type="primary" @click="next('2')" :loading="nextLoading"
              >下一步</el-button
            >
          </div>
        </div>

        <div class="box box-success" v-if="active === 2">
          <div class="success-icon">
            <i class="el-icon-success"></i>
          </div>
          <div class="success">设置密保问题成功！</div>
        </div>
      </div>
    </common-page>
    <!--    </common-edit-dialog>-->
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  byDictType,
  querySecurityByUserName,
  queryUserSecurity,
  updateUserPwdAnswer,
  queryQuestionByUserName,
  sendPhoneVerCodeForQueryPwdAnswer,
  checkPhoneVerCodeForQueryPwdAnswer,
  sendEmailVerCodeForQueryPwdAnswer,
  checkEmailVerCodeForQueryPwdAnswer,
  getMsgCodeValidTime,
} from "@/api/person/index";

import Cookies from "js-cookie";
import { decode, encode } from "@/utils/aesUtils";

var timeFlag = null;
export default {
  props: {
    showQuesDialog: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      dialogTitle: "设置密保问题", // 标题
      questionList: [],
      dialogShow: false, // 是否显示
      activeTab: "1",
      phoneYzm: false,
      setValid: 10, //验证码有效期(分钟)
      phoneYzmTimes: 60,
      userForm: {
        yzmPhone: "",
        yzmEmail: "",
      },
      form: {
        firstQuestionId: "",
        secondQuestionId: "",
        thirdQuestionId: "",
        firstAnswer: "",
        secondAnswer: "",
        thirdAnswer: "",
      },
      quesRules: {
        firstQuestionId: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
        firstAnswer: [
          {
            required: true,
            message: "请输入问题一答案",
            trigger: "blur",
          },
        ],
        secondQuestionId: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
        secondAnswer: [
          {
            required: true,
            message: "请输入问题二答案",
            trigger: "blur",
          },
        ],
        thirdQuestionId: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
        thirdAnswer: [
          {
            required: true,
            message: "请输入问题三答案",
            trigger: "blur",
          },
        ],
      },
      loading: false,
      formLoading: true,
      active: 0,
      nextLoading: false,
      rules: {
        yzmPhone: [
          { required: true, message: "请输入验证码", trigger: "blur" },
        ],
        yzmEmail: [
          { required: true, message: "请输入验证码", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["name", "nickName"]),
  },
  methods: {
    /**
     * 获取问题列表
     */
    getQuestionList() {
      return new Promise((resolve, reject) => {
        byDictType({ dictType: "SYS_PWD_QUESTION_" }).then((res) => {
          if (res && res.code === 200) {
            resolve(res);
          } else {
            reject(res);
          }
        });
      });
    },
    /**
     * 获取已设置的问题
     */
    getQuestionListByuser() {
      return new Promise((resolve, reject) => {
        queryQuestionByUserName({ userName: this.name }).then((res) => {
          if (res && res.code === 200) {
            resolve(res);
          } else {
            reject(res);
          }
        });
      });
    },
    /**
     * 获取已设置的问题答案
     */
    getQueryUserSecurity() {
      return new Promise((resolve, reject) => {
        queryUserSecurity().then((res) => {
          if (res && res.code === 200) {
            resolve(res);
          } else {
            reject(res);
          }
        });
      });
    },
    /**
     * 关闭
     */
    close() {
      this.$refs.form.resetFields();
      this.dialogShow = false;
    },
    /**
     * 显示
     */
    show(data) {
      this.active = 0;
      if (timeFlag) clearInterval(timeFlag);
      const msgVerCodeId = Cookies.get("msgVerCodeId");
      this.form.msgVerCodeId = msgVerCodeId === undefined ? "" : msgVerCodeId;
      this.phoneYzm = false;
      this.phoneYzmTimes = 60;
      this.dialogShow = true;
      this.formLoading = true;
      this.userForm = data;
      this.getMsgCodeValidTime();
    },
    submit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let params = Object.assign({}, this.form, {
            firstAnswer: encode(this.form.firstAnswer),
            secondAnswer: encode(this.form.secondAnswer),
            thirdAnswer: encode(this.form.thirdAnswer),
          });
          this.loading = true;
          this.nextLoading = true;
          updateUserPwdAnswer(params)
            .then((res) => {
              if (res && res.code === 200) {
                if (this.active++ > 2) this.active = 0;
                // this.$GlobalSuccessMessage('编辑成功')
              } else {
                this.$GlobalErrorConfirm("操作失败", res.msg).then();
              }
            })
            .finally(() => (this.nextLoading = false));
        }
      });
    },
    changeFun(e) {
      for (let index in this.questionList) {
        this.questionList[index].disabled =
          this.questionList[index].dictValue == this.form.firstQuestionId ||
          this.questionList[index].dictValue == this.form.secondQuestionId ||
          this.questionList[index].dictValue == this.form.thirdQuestionId;
      }
      this.$forceUpdate();
    },

    /**
     * 获取验证码有效期
     */
    getMsgCodeValidTime() {
      getMsgCodeValidTime().then((res) => {
        if (res && res.code === 200) {
          this.setValid = parseInt(res.msg);
        }
      });
    },
    /**
     * 切换验证类型
     */
    verifyChange(type) {
      if (timeFlag) clearInterval(timeFlag);
      const msgVerCodeId = Cookies.get("msgVerCodeId");
      this.form.msgVerCodeId = msgVerCodeId === undefined ? "" : msgVerCodeId;
      this.phoneYzm = false;
      this.phoneYzmTimes = 60;
      this.activeTab = type;
    },

    /**
     * 短信发送验证
     */
    sendPhoneVerCodeForQueryPwdAnswer() {
      sendPhoneVerCodeForQueryPwdAnswer({ userName: this.userForm.userName })
        .then((res) => {
          if (res && res.code === 200) {
            this.phoneYzm = true;
            this.userForm.msgVerCodeId = res.data.msgVerCodeId;
            let expiresTime = new Date().getTime();
            Cookies.set("msgVerCodeId", res.data.msgVerCodeId, {
              expires: new Date(
                expiresTime + 60 * 1000 * parseInt(this.setValid)
              ),
            });
            // this.form.createTime = this.utils.getNowTime();
            timeFlag = setInterval(() => {
              this.phoneYzmTimes--;
              if (this.phoneYzmTimes === 0) {
                this.phoneYzm = false;
                this.phoneYzmTimes = 60;
                // this.form.msgVerCodeId = ''
                clearInterval(timeFlag);
              }
            }, 1000);
          } else {
            this.$GlobalErrorConfirm("获取失败", res.msg).then();
          }
        })
        .finally();
    },
    /**
     * 邮箱发送验证
     */
    sendEmailVerCodeForQueryPwdAnswer() {
      sendEmailVerCodeForQueryPwdAnswer({ userName: this.userForm.userName })
        .then((res) => {
          if (res && res.code === 200) {
            this.phoneYzm = true;
            this.userForm.msgVerCodeId = res.data.msgVerCodeId;
            let expiresTime = new Date().getTime();
            Cookies.set("msgVerCodeId", res.data.msgVerCodeId, {
              expires: new Date(
                expiresTime + 60 * 1000 * parseInt(this.setValid)
              ),
            });
            timeFlag = setInterval(() => {
              this.phoneYzmTimes--;
              if (this.phoneYzmTimes === 0) {
                this.phoneYzm = false;
                this.phoneYzmTimes = 60;
                // this.form.msgVerCodeId = ''
                clearInterval(timeFlag);
              }
            }, 1000);
          } else {
            this.$GlobalErrorConfirm("获取失败", res.msg).then();
          }
        })
        .finally();
    },
    /**
     * 下一步
     */
    next(type) {
      if (type === "1") {
        this.$refs["userForm"].validate((valid) => {
          if (valid) {
            this.nextLoading = true;
            if (this.activeTab === "1") {
              this.checkPhone();
            } else {
              this.checkEmail();
            }
          }
        });
      } else {
        this.submit();
      }
    },
    /**
     * 验证手机号
     */
    checkPhone() {
      this.nextLoading = true;
      checkPhoneVerCodeForQueryPwdAnswer({
        // po: {
        redisKey: "redis_check_old_phone_vercode_",
        userName: this.userForm.userName,
        msgVerCodeId: this.userForm.msgVerCodeId,
        msgVerCode: this.userForm.yzmPhone,
        phone: this.userForm.phonenumber,
        businessName: "queryPwdAnswer_sendTo_phone",
        // },
      })
        .then((res) => {
          if (res && res.code === 200) {
            this.getQuestionInfo();
            this.userForm.yzmPhone = "";
            this.phoneYzm = false;
            this.phoneYzmTimes = 60;
            this.userForm.msgVerCodeId = "";
            if (timeFlag) clearInterval(timeFlag);
            if (this.active++ > 2) this.active = 0;
          } else {
            this.$GlobalErrorConfirm("操作失败", res.msg).then();
          }
        })
        .finally(() => (this.nextLoading = false));
    },
    /**
     * 验证邮箱
     */
    checkEmail() {
      this.nextLoading = true;
      checkEmailVerCodeForQueryPwdAnswer({
        // po: {
        redisKey: "redis_send_old_email_vercode_",
        userName: this.userForm.userName,
        msgVerCodeId: this.userForm.msgVerCodeId,
        msgVerCode: this.userForm.yzmEmail,
        email: this.userForm.email,
        businessName: "queryPwdAnswer_sendTo_email",
        // },
      })
        .then((res) => {
          if (res && res.code === 200) {
            this.getQuestionInfo();
            this.userForm.yzmEmail = "";
            this.phoneYzm = false;
            this.phoneYzmTimes = 60;
            this.userForm.msgVerCodeId = "";
            clearInterval(timeFlag);
            if (this.active++ > 2) this.active = 0;
          } else {
            this.$GlobalErrorConfirm("操作失败", res.msg).then();
          }
        })
        .finally(() => (this.nextLoading = false));
    },

    /**
     * 获取密保问题相关信息
     */
    getQuestionInfo() {
      Promise.all([
        this.getQueryUserSecurity(),
        this.getQuestionListByuser(),
        this.getQuestionList(),
      ])
        .then((res) => {
          this.form.firstAnswer = res[0].data.firstAnswer
            ? decode(res[0].data.firstAnswer)
            : "";
          this.form.secondAnswer = res[0].data.secondAnswer
            ? decode(res[0].data.secondAnswer)
            : "";
          this.form.thirdAnswer = res[0].data.thirdAnswer
            ? decode(res[0].data.thirdAnswer)
            : "";

          this.form.firstQuestionId =
            res[1].data.firstQuestion && res[1].data.firstQuestion.dictValue
              ? res[1].data.firstQuestion.dictValue
              : "";
          this.form.secondQuestionId =
            res[1].data.secondQuestion && res[1].data.secondQuestion.dictValue
              ? res[1].data.secondQuestion.dictValue
              : "";
          this.form.thirdQuestionId =
            res[1].data.thirdQuestion && res[1].data.thirdQuestion.dictValue
              ? res[1].data.thirdQuestion.dictValue
              : "";

          this.questionList = res[2].data;
          this.changeFun();
        })
        .finally(() => (this.formLoading = false));
    },

    /**
     * 返回
     */
    back() {
      this.$emit("changeDiv");
    },
  },
  created() {},
};
</script>

<style scoped lang="scss">
.user-ques-edit-wrap {
  padding: 20px;
  box-sizing: border-box;
  margin-top: 50px;

  .box {
    width: 400px;
    margin: 20px auto 60px;
    /*height: 200px;*/

    .mode-div {
      width: 100%;
      height: 50px;
      font-size: 16px;
      border-bottom: solid 1px #eee;
      margin-bottom: 20px;

      .active {
        cursor: pointer;
        // width: 110px;
        padding: 0 20px;
        height: 50px;
        line-height: 50px;
        float: left;
        color: var(--theme-color) !important;
        border-bottom: solid 1px var(--theme-color) !important;
      }

      .no-active {
        cursor: pointer;
        // width: 110px;
        padding: 0 20px;
        height: 50px;
        line-height: 50px;
        float: left;
        color: #666;
        border-bottom: solid 1px #eee;
      }
    }

    .info {
      padding: 20px 0 0;
      font-size: 15px;
    }

    .get-box {
      padding-bottom: 40px;

      .input-box {
        display: flex;
        align-items: center;
        margin-top: 20px;
      }

      .disabled {
        background-color: #ddd;
        border-color: #ddd;
        color: var(--theme-color) !important;
        cursor: not-allowed;
      }

      .notice {
        font-size: 13px;
        color: #999;
        padding-top: 8px;
      }

      .btn {
        width: 210px !important;
        text-align: center;
        background: var(--theme-color) !important;
        color: #fff;
        height: 32px;
        line-height: 32px;
        cursor: pointer;
      }
    }

    .el-button {
      width: 100%;
    }

    .success-icon {
      width: 100%;
      display: flex;
      justify-content: center;

      .el-icon-success {
        font-size: 60px;
        color: #67c23a;
      }
    }

    .success {
      margin-top: 20px;
      text-align: center;
      font-size: 15px;
    }
  }

  .question-list {
    width: 50%;
    margin: 40px auto;

    .submit-btn {
      margin-top: 40px;
      width: 100%;
      display: flex;
      justify-content: center;

      .el-button {
        width: 50%;
      }
    }
  }

  .success-icon {
    width: 100%;
    display: flex;
    justify-content: center;

    .el-icon-success {
      font-size: 60px;
      color: #67c23a;
    }
  }

  .success {
    margin-top: 20px;
    text-align: center;
    font-size: 15px;
  }

  .box-success {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-top: 60px;
    height: 200px;
  }
}

::v-deep .el-form {
  .el-form-item__content {
    display: flex;
    align-items: center;
  }
}
</style>
